import crypto from 'crypto';


export class AES {
  private args: { cipherEncoding: string; clearEncoding: string; aes128Ecb: string };

  constructor(args: { cipherEncoding: string, clearEncoding: string, aes128Ecb: string } = {
    cipherEncoding: 'base64',
    clearEncoding: 'utf8',
    aes128Ecb: 'aes-128-ecb',
  }) {
    this.args = args
  }

  encrypt({data, key, iv = ''}) {
    const cipherChunks = []
    const cipher = crypto.createCipheriv(this.args.aes128Ecb, key, iv)
    cipher.setAutoPadding(true)
    cipherChunks.push(cipher.update(data, 'utf8', this.args.cipherEncoding))
    cipherChunks.push(cipher.final(this.args.cipherEncoding))
    return cipherChunks.join('')
  }

  decrypt({data, key, iv = ''}) {
    const cipherChunks = []
    const decipher = crypto.createDecipheriv(this.args.aes128Ecb, key, iv)
    decipher.setAutoPadding(true)
    cipherChunks.push(decipher.update(data, this.args.cipherEncoding,
        this.args.clearEncoding))
    cipherChunks.push(decipher.final(this.args.clearEncoding))
    return cipherChunks.join('')
  }
}